//
//  MCBonusContractViewController.m
//  TLYL
//
//  Created by MC on 2017/11/1.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCBonusContractViewController.h"
#import "MCBonusContractHeaderView.h"
#import "MCContractMgtBaseModel.h"
#import "MCMyBonusContractListModel.h"
#import "MCMyBonusContractTableViewCell.h"
#import "MCMyXiaJiBonusContractListModel.h"
#import "MCBonusOneKeySettlementModel.h"
#import "MCMineInfoModel.h"
#import "MCModifyOrSignBonusContractViewController.h"
#import "MCContractContentModelsData.h"
#import "MCAgreeHigherBonusContractViewController.h"
#import "MCClickBonusSettlementModel.h"
#import "MCBonusJieSuanViewController.h"
#import "MCGetBonusPeriodModel.h"
#import "MCPopAlertView.h"
#import "MCBonusGetSystemTypeModel.h"
#import "MCMMIputView.h"

#define MORENCOUNT @"15"
@interface MCBonusContractViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
MGBaseSwipeTableViewCellDelegate
>

typedef void(^Compeletion)(BOOL result, NSDictionary *data );
typedef void(^RefreashCompeletion)(BOOL result, NSDictionary *data1,NSDictionary *data2 );

@property(nonatomic, strong) MCBonusContractHeaderView * headerView;
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)ExceptionView * exceptionView;
@property(nonatomic, strong)NSMutableArray * xiaJiDataMarray;

//查看我的分红契约列表
@property(nonatomic, strong)MCMyBonusContractListModel * myBonusContractListModel;
@property(nonatomic, strong)MCMyBonusContractListDataModel* myBonusContractListData;

//获取下级的分红契约列表
@property(nonatomic, strong)MCMyXiaJiBonusContractListModel * xiaJiBonusContractListModel;
@property(nonatomic, strong)MCMyXiaJiBonusContractListDataModel * xiajiListData;

////查看 当前登录用户 是否有新的分红契约
//@property(nonatomic, strong)MCGetSelfContractStateModel *getSelfContractStateModel;

@property(nonatomic, strong)NSString * CurrentPageIndex;
@property(nonatomic, strong)NSString * subUserName;

//一键结算
@property(nonatomic, strong)MCBonusOneKeySettlementModel * oneKeySettlementModel;
@property(nonatomic, strong)NSString * LockState;//是否显示“一键结算”（1：显示，0：不显示）

//分红结算
@property (nonatomic,strong)MCClickBonusSettlementModel * clickBonusSettlementModel;


//获取分红周期列表（新制度）
@property (nonatomic,strong)MCGetBonusPeriodModel * getBonusPeriodModel;
@property (nonatomic,strong)MCGetBonusPeriodDataModel * getBonusPeriodDataModel;
@property (nonatomic,assign)int T;
@property (nonatomic,strong)NSDictionary * dic1;
@property (nonatomic,strong)NSDictionary * dic2;

@property(nonatomic, strong)MCNaviSelectedPopView *popView1;
@property(nonatomic, assign) BOOL  isShowPopView1;
@property(nonatomic, weak)  MCMMIputView * viewPop1;
@property(nonatomic,assign)BOOL isHadRefreashUI;

@property(nonatomic, strong)MCBaseGetSystemTypeModel * SystemType;//分红类型
@property(nonatomic, strong)MCBaseGetSystemTypeModel * selected_SystemType;
@property(nonatomic, strong)MCBonusGetSystemTypeModel * bonusGetSystemTypeModel;

@property(nonatomic, strong)NSString * ContractState ;//   是    Int    签约状态：-1全部,0修改待确认，1已签约
@property (nonatomic,strong)NSString *IsSubContract    ;//Int    是否与下级签约：0=否，1=是
@property (nonatomic,assign)BOOL HaveNewContractState;

@end

@implementation MCBonusContractViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setProperty];
    
    [self setNav];
    
    [self createUI];
    
    [self checkSystemType];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    MCContractContentModelsData * data = [MCContractContentModelsData sharedMCContractContentModelsData];
    [data removeDataSource];
//    if (!_isHadRefreashUI) {
//       [self checkSystemType];
//    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

}


#pragma mark-
-(void) cancelTableEditClick: (id) sender{
    [_tableView setEditing: NO animated: YES];
}

-(NSArray *) createRightButtons: (int) number andTitle:(NSArray *)titles{

    NSMutableArray * result = [NSMutableArray array];
    NSArray * colors;
    if (number==1) {
        colors=@[RGB(228,66,65)];
    }else{
        colors=@[RGB(248,193,1),RGB(228,66,65)];
    }
//    UIColor * colors[2] = {RGB(248,193,1),RGB(228,66,65)};
    for (int i = 0; i < number; ++i){
        MGSwipeButton * button = [MGSwipeButton buttonWithTitle:titles[i] backgroundColor:colors[i] callback:^BOOL(MGSwipeTableCell * sender){
            BOOL autoHide = i != 0;
            return autoHide;
        }];
        [result addObject:button];
    }
    return result;
}



#if TEST_USE_MG_DELEGATE
-(nullable NSArray<UIView*>*) swipeTableCell:(nonnull MCXiaJiWageContractTableViewCell*) cell swipeButtonsForDirection:(MGSwipeDirection)direction
                               swipeSettings:(nonnull MGSwipeSettings*) swipeSettings expansionSettings:(nonnull MGSwipeExpansionSettings*) expansionSettings{
    
    swipeSettings.transition = MGSwipeTransitionBorder;
    if (direction == MGSwipeDirectionLeftToRight) {
        return nil;
    }else {
        expansionSettings.buttonIndex = 1;
        expansionSettings.fillOnTrigger = YES;
        return [self createRightButtons:1];
    }
}
#endif

-(BOOL) swipeTableCell:(nonnull MCMyBonusContractTableViewCell*) cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL) fromExpansion
{
    NSLog(@"Delegate: button tapped, %@ position, index %d, from Expansion: %@",
          direction == MGSwipeDirectionLeftToRight ? @"left" : @"right", (int)index, fromExpansion ? @"YES" : @"NO");
    
    if (direction == MGSwipeDirectionRightToLeft && (index == 0||index == 1)) {
        //delete button
        NSIndexPath * indexPath = [_tableView indexPathForCell:cell];
        if (_xiaJiDataMarray.count>indexPath.section) {
            MCMyXiaJiBonusContractListDeatailDataModel *models = _xiaJiDataMarray[indexPath.section];
            NSArray * stateArray = [self GetTouchArrayWithState:models.State];
            NSLog(@"-----点击%@----",stateArray[index]);
            __weak __typeof__ (self) wself = self;
            if ([stateArray[index] isEqualToString:@"签订契约"]) {
#pragma mark-跳转【签订契约】
                MCModifyOrSignBonusContractViewController * VC = [[MCModifyOrSignBonusContractViewController alloc]init];
                VC.models=models;
                VC.Type=MCModifyOrSignBonusContractType_Sign;
                VC.SystemType=wself.SystemType;
                VC.goBackBlock = ^(NSInteger type) {

                    [wself onlyLoadData];

                };
                [self.navigationController pushViewController:VC animated:YES];
                
            }else if ([stateArray[index] isEqualToString:@"更改契约"]){
#pragma mark-跳转【更改契约】
                MCModifyOrSignBonusContractViewController * VC = [[MCModifyOrSignBonusContractViewController alloc]init];
                VC.models=models;
                VC.Type=MCModifyOrSignBonusContractType_Modify;
                VC.SystemType=wself.SystemType;
                VC.goBackBlock = ^(NSInteger type) {

                    [wself onlyLoadData];
                    
                };
                [self.navigationController pushViewController:VC animated:YES];
                
#pragma mark-点击【分红结算】
            }else if ([stateArray[index] isEqualToString:@"分红结算"]){
                [self ClickBonusSettlement:models];
            }
        }

        return YES; //Don't autohide to improve delete expansion animation
    }
    
    return YES;
}

-(void) tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"Tapped accessory button");
}


#pragma mark==================setProperty======================
-(void)setProperty{
    self.view.backgroundColor=RGB(231, 231, 231);
    self.navigationItem.title = @"分红契约";
    _xiaJiDataMarray=[[NSMutableArray alloc]init];
    _CurrentPageIndex=@"1";
    _subUserName=@"";
    self.isHadRefreashUI=NO;
    self.tableView.mj_footer.hidden=YES;
    _ContractState = @"-1";//默认 “全部”
    _IsSubContract=@"";
    _HaveNewContractState=NO;
}

#pragma mark ====================设置导航栏========================
-(void)setNav{
    UIButton *rightBtn = [[UIButton alloc] init];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"debss"] forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn sizeToFit];
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchDown];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma mark==================createUI======================
-(void)createUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self onlyLoadData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_tableView];

    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(0);
        make.left.equalTo(self.view.mas_left).offset(13);
        make.right.equalTo(self.view.mas_right).offset(-13);
        make.bottom.equalTo(self.view.mas_bottom).offset(-kTabBarHeight);
    }];
}

-(void)rightBtnAction{
    if (_isShowPopView1) {
        _isShowPopView1=NO;
        [self.popView1 dismiss];
        
    }else{
        _isShowPopView1=YES;
        
        typeof(self) weakself = self;
        
        self.popView1.block = ^(NSInteger type) {
            
            if (type==0) {
                
            }else if (type==1){
                
                MCBonusGetSystemTypeModel * bonusGetSystemTypeModel = [MCBonusGetSystemTypeModel sharedMCBonusGetSystemTypeModel];
                
                NSArray * arr = bonusGetSystemTypeModel.nameDataSource;
                NSArray * Marr =bonusGetSystemTypeModel.bonusDataSource;
                if (arr.count<1) {
                    return ;
                }
                weakself.viewPop1.dataArray =  arr;
                [weakself.viewPop1 show];
                weakself.viewPop1.cellDidSelectedTop = ^(NSInteger i) {
                    
                    MCBaseGetSystemTypeModel * model =  Marr[i];
                   
                    weakself.selected_SystemType=model;
                    weakself.popView1.label2.text=arr[i];
                    [weakself.viewPop1 hiden];
                    
                };
                
            }else if (type==2){
                

                //-1=全部，0=待确认，1=已签约，2=未签约
                NSArray * arr = @[@"全部",@"待确认",@"已签约",@"未签约"];
                NSDictionary * ContractStateDic=@{@"全部":@"-1",@"待确认":@"0",@"已签约":@"1",@"未签约":@"2"};
                weakself.viewPop1.dataArray =  arr;
                [weakself.viewPop1 show];
                weakself.viewPop1.cellDidSelectedTop = ^(NSInteger i) {
                    
                    weakself.ContractState=ContractStateDic[arr[i]];
                    weakself.popView1.label3.text=arr[i];
                    [weakself.viewPop1 hiden];
                    
                };
                
#pragma mark-搜索
            }else if (type==8){
                
                weakself.isShowPopView1=NO;
                [weakself dismissAllPopView1];
                
                weakself.subUserName = weakself.popView1.tf1.text;
                [weakself.xiaJiDataMarray removeAllObjects];
                weakself.CurrentPageIndex = @"1";
                
                if (weakself.selected_SystemType) {
                    weakself.SystemType=weakself.selected_SystemType;
                }
                

                [weakself onlyLoadData];

            }
        };
        
        self.popView1.frame= CGRectMake(0, kStatusBarAndNavigationBarHeight, G_SCREENWIDTH, G_SCREENHEIGHT);
        [self.popView1 showPopView];
    }
}

#pragma mark ========================tableView 代理相关========================
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (_xiaJiDataMarray.count<1) {
        return 1;
    }else{
        return _xiaJiDataMarray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return [MCBonusContractHeaderView computeHeight:_myBonusContractListData andLockState:_xiajiListData.LockState andHaveNewContractState:_HaveNewContractState];
    }
    return 0.00001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    __weak __typeof__ (self) wself = self;
    
    if (section==0) {
#pragma mark-点击一键结算
        self.headerView.settleBlock = ^{
            NSLog(@"-----一键结算------");
            [wself oneKeySettlement];
        };
#pragma mark-点击新契约
        self.headerView.goToContractBlock = ^{
            MCAgreeHigherBonusContractViewController * VC = [[MCAgreeHigherBonusContractViewController alloc]init];
            VC.SystemType = wself.SystemType;
            VC.goBackBlock = ^{
              [wself onlyLoadData];
            };
            [wself.navigationController pushViewController:VC animated:YES];
        };
        return self.headerView;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_xiaJiDataMarray.count<1) {
        return 0.0001;
    }
    return [MCMyBonusContractTableViewCell computeHeight:nil];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *reuseIdentifier_2 =[NSString stringWithFormat:@"MCMyBonusContractTableViewCell-%ld-%ld",(long)indexPath.section,(long)indexPath.row];
    
    MCMyBonusContractTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier_2];
    if (!cell2) {
        cell2 = [[MCMyBonusContractTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier_2];
        cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (_xiaJiDataMarray.count>indexPath.section) {
        cell2.dataSource=_xiaJiDataMarray[indexPath.section];
    }
    //设置操作按钮的显示和隐藏
    [cell2 setIsSubContract:_IsSubContract];
    cell2.accessoryType = UITableViewCellAccessoryNone;
    cell2.delegate = self;
    cell2.allowsMultipleSwipe = NO;
    cell2.layer.cornerRadius = 6;
    cell2.clipsToBounds = YES;
    
//#if !TEST_USE_MG_DELEGATE
    //设置Cell是否能滑动
    if ([[NSString stringWithFormat:@"%@",_IsSubContract] isEqualToString:@"1"]) {
        cell2.rightSwipeSettings.transition = MGSwipeTransitionStatic;
        cell2.rightExpansion.buttonIndex = 1;
        cell2.rightExpansion.buttonIndex = -1;
        cell2.rightExpansion.fillOnTrigger = YES;
        
        if (_xiaJiDataMarray.count>indexPath.section) {
            MCMyXiaJiBonusContractListDeatailDataModel *models = _xiaJiDataMarray[indexPath.section];
            NSArray * stateArray = [self GetTouchArrayWithState:models.State];
            cell2.rightButtons = [self createRightButtons:(int)stateArray.count andTitle:stateArray];
            
        }else{
            cell2.rightButtons = [self createRightButtons:1 andTitle:@[@"..."]];
        }
    }else{

        if (_xiaJiDataMarray.count>indexPath.section) {
            MCMyXiaJiBonusContractListDeatailDataModel *models = _xiaJiDataMarray[indexPath.section];
            if ([_LockState intValue]== 1 && [models.State intValue] != 2) {
                cell2.rightSwipeSettings.transition = MGSwipeTransitionStatic;
                cell2.rightExpansion.buttonIndex = 1;
                cell2.rightExpansion.buttonIndex = -1;
                cell2.rightExpansion.fillOnTrigger = YES;
                cell2.rightButtons = [self createRightButtons:1 andTitle:@[@"分红结算"]];
                [cell2 setIsSubContract:@"1"];
            }else{
                
                cell2.rightSwipeSettings.transition = MGSwipeTransitionStatic;
                cell2.rightExpansion.buttonIndex = 0;
                cell2.rightExpansion.fillOnTrigger = NO;
                cell2.rightButtons = [self createRightButtons:0 andTitle:@[@"..."]];
                
            }
        }else{
            cell2.rightSwipeSettings.transition = MGSwipeTransitionStatic;
            cell2.rightExpansion.buttonIndex = 0;
            cell2.rightExpansion.fillOnTrigger = NO;
            cell2.rightButtons = [self createRightButtons:0 andTitle:@[@"..."]];
        }
        

        
    }
    
//#endif
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    cell2.bonusBlock = ^{
        MCMyBonusContractTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        [cell showSwipe:MGSwipeDirectionRightToLeft animated:YES completion:^(BOOL finished) {

        }];
    };
    return cell2;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark-Http
#pragma mark-一键结算
-(void)oneKeySettlement{
    if (_getBonusPeriodDataModel&&_getBonusPeriodDataModel.EndTime.length>0&&_getBonusPeriodDataModel.BeginTime.length>0) {
        [self PopAlertTypeContractMgt_OneKeySettlement];
    }else{
        
        [BKIndicationView showInView:self.view];
        [self loadBonusPeriodData:^(BOOL result, NSDictionary *data) {
            [BKIndicationView dismiss];
            if (result) {
                [self PopAlertTypeContractMgt_OneKeySettlement];
            }else{                
                [SVProgressHUD showInfoWithStatus:@"获取结算周期失败！"];
            }
        }];
    }
}

-(void)PopAlertTypeContractMgt_OneKeySettlement{
    
    MCPopAlertView *mcAlertView = [[MCPopAlertView alloc]initWithType:MCPopAlertTypeContractMgt_OneKeySettlement Title:@"一键结算" leftBtn:@"确定" rightBtn:@"取消" andGetBonusPeriodDataModel:_getBonusPeriodDataModel andSystemTypeModel:_SystemType];
    
    mcAlertView.resultIndex = ^(NSInteger index){
        if (index==1) {
            
            [self DoOneKeySettlement];
            
        }
    };
    [mcAlertView showXLAlertView];
}

-(void)DoOneKeySettlement{
    //Sign    是    Int    0=顶级用户，1=直属下级（前端传固定值：1）
    //BeginTime    是    String    开始时间
    //EndTime    是    String    结束时间
    //TypeParameterId    是    Int    分红类型 ID
    //TypeName    是    String    分红类型名称
    
  

    
    MCMineInfoModel * mineInfoModel=[MCMineInfoModel sharedMCMineInfoModel];
    NSString * UserName;
    if (mineInfoModel.UserName.length>1) {
        UserName=mineInfoModel.UserName;
    }else{
        UserName=[[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
    }
    NSDictionary * dic=@{
                         @"Sign":@"1",
                         @"BeginTime":_getBonusPeriodDataModel.BeginTime,
                         @"EndTime":_getBonusPeriodDataModel.EndTime,
                         @"TypeParameterId":_SystemType.Id,
                         @"TypeName":_SystemType.Name
                         //                         @"UserID" : [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"],
                         //                         @"UserName": UserName,
                         
                         };
    __weak __typeof__ (self) wself = self;
    [BKIndicationView showInView:self.view];
    MCBonusOneKeySettlementModel * oneKeySettlementModel = [[MCBonusOneKeySettlementModel alloc]initWithDic:dic];
    [oneKeySettlementModel refreashDataAndShow];
    self.oneKeySettlementModel = oneKeySettlementModel;
    
    oneKeySettlementModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        //        [SVProgressHUD showInfoWithStatus:@"结算失败！"];
        [BKIndicationView dismiss];
    };
    
    oneKeySettlementModel.callBackSuccessBlock = ^(id manager) {
        [SVProgressHUD showInfoWithStatus:@"结算成功！"];
        [BKIndicationView dismiss];
        [wself performSelector:@selector(delyRefreashData) withObject:nil afterDelay:0.5];
    };
}

-(void)delyRefreashData{
    
    [self onlyLoadData];
}

#pragma mark-分红结算
-(void)ClickBonusSettlement:( MCMyXiaJiBonusContractListDeatailDataModel * )models{
    if (!models.UserID||!models.UserName) {
        return;
    }
    if (!_SystemType) {
        return;
    }
    __weak __typeof__ (self) wself = self;
    MCBonusJieSuanViewController * vc = [[MCBonusJieSuanViewController alloc]init];
    vc.SystemType=_SystemType;
    vc.models = models;
    vc.goBackBlock = ^{
        [wself onlyLoadData];
    };
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)checkSystemType{
    __weak __typeof__ (self) wself = self;
    
    /*
     * 先确保SystemType有值
     */
    MCBonusGetSystemTypeModel * bonusGetSystemTypeModel = [MCBonusGetSystemTypeModel sharedMCBonusGetSystemTypeModel];
    
    
    if (bonusGetSystemTypeModel.bonusDataSource.count<1) {
        
        [BKIndicationView showInView:self.view];
        MCBonusGetSystemTypeModel * bonusGetSystemTypeModel = [MCBonusGetSystemTypeModel sharedMCBonusGetSystemTypeModel];
        [bonusGetSystemTypeModel refreashDataAndShow];
        self.bonusGetSystemTypeModel=bonusGetSystemTypeModel;
        bonusGetSystemTypeModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
            [BKIndicationView dismiss];
            wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                [wself.exceptionView dismiss];
                wself.exceptionView = nil;
                [wself checkSystemType];
            }];
            [wself.exceptionView addAction:action];
            [wself.exceptionView showInView:wself.view];
        };
        bonusGetSystemTypeModel.callBackSuccessBlock = ^(id manager) {
            [BKIndicationView dismiss];
            [wself.bonusGetSystemTypeModel setDataSource:manager];
            NSArray * arr = manager;
            if (arr.count<1) {
                //无数据
                self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoData];
                [self.exceptionView showInView:self.view];
            }else{
                [wself checkSystemType];
            }
            
        };
        
    }else{
        
        _SystemType = bonusGetSystemTypeModel.bonusDataSource[0];
        [self onlyLoadData];
    }
}
#pragma mark-下拉刷新
- (void)onlyLoadData{
        
     __weak __typeof__ (self) wself = self;
  
    [BKIndicationView showInView:self.view];
    //    self.tableView.mj_footer.hidden=NO;
    _CurrentPageIndex=@"1";
    [self.exceptionView dismiss];
    self.exceptionView = nil;
    self.tableView.mj_footer.hidden=YES;
    
    [self refreashData:^(BOOL result, NSDictionary *data1, NSDictionary *data2) {
        //通知主线程刷新
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            [BKIndicationView dismiss];
            [wself.tableView.mj_header endRefreshing];
            [wself.tableView.mj_footer endRefreshing];
            if (result) {
                wself.isHadRefreashUI=YES;
                [wself.exceptionView dismiss];
                wself.exceptionView = nil;
                [wself setDataWithDic1:data1 andDic2:data2];
            }else{
                wself.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
                ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                    [wself.exceptionView dismiss];
                    wself.exceptionView = nil;
                    [wself onlyLoadData];
                }];
                [wself.exceptionView addAction:action];
                [wself.exceptionView showInView:wself.view];
            }
        });
    }];
    
    
    /*
     * 分红周期获取
     */
    [self loadBonusPeriodData:^(BOOL result, NSDictionary *data) {
        
    }];

}

-(void)loadBonusPeriodData:(Compeletion)compeletion{
    
    __weak __typeof__ (self) wself = self;
    
    //    TypeParameterId    是    int    分红类型 ID
    //    Number    是    Int    查询周期数 ( Number =1 查询当前周期信息，Number > 1,查询前Number条周期信息)
    NSDictionary * dic = @{
                           @"TypeParameterId":_SystemType.Id,
                           @"Number":@"1"
                           };
    MCGetBonusPeriodModel * getBonusPeriodModel = [[MCGetBonusPeriodModel alloc]initWithDic:dic];
    [getBonusPeriodModel refreashDataAndShow];
    self.getBonusPeriodModel = getBonusPeriodModel;
    
    getBonusPeriodModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
       compeletion(NO,nil);
    };
    getBonusPeriodModel.callBackSuccessBlock = ^(id manager) {
        NSDictionary * dic = manager;
        
        [wself setBonusPeriodData:dic];
        
        compeletion(YES,dic);
        
    };
}
-(void)setBonusPeriodData:(NSDictionary *)dic{
    
    MCGetBonusPeriodDataModel * getBonusPeriodDataModel = [MCGetBonusPeriodDataModel mj_objectWithKeyValues:dic];
    _getBonusPeriodDataModel=getBonusPeriodDataModel;

}

-(void)refreashData:(RefreashCompeletion)compeletion{
    __weak __typeof__ (self) wself = self;
    
    _T = 0;
//    UserID    是    String    当前登录用户ID
//    TypeParameterId    是    Int    分红类型id，从 get_system_type获取
    NSDictionary * dic=@{
                         @"UserID" : [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"],
                         @"TypeParameterId":_SystemType.Id
        
//                         @"IsState":@"1"
                         };
    MCMyBonusContractListModel * myBonusContractListModel = [[MCMyBonusContractListModel alloc]initWithDic:dic];
    [myBonusContractListModel refreashDataAndShow];
    self.myBonusContractListModel = myBonusContractListModel;
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_group_async(group, quene, ^{
        
        myBonusContractListModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
            NSLog(@"complete task 1-NO");
            dispatch_semaphore_signal(semaphore);
        };
        
        myBonusContractListModel.callBackSuccessBlock = ^(id manager) {
            NSLog(@"complete task 1-YES");
            dispatch_semaphore_signal(semaphore);
            wself.T++;
            wself.dic1=manager;
        };
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });

    
//    searchName (旧：UserName )    是    String    搜索用户名（搜索时传搜索值，否则传空串）
//    TypeParameterId    是    Int    分红类型id
//    ContractState    是    Int    签约状态：0修改待确认，1已签约
//    CurrentPageIndex    是    Int    当前页下标（第一页为1，后续页码依次加1）
//    CurrentPageSize    是    Int    当前页请求条目数
    
    
    NSDictionary * x_dic = @{
                             @"searchName":_subUserName,
                             @"TypeParameterId":_SystemType.Id,
                             @"CurrentPageIndex":_CurrentPageIndex,
                             @"ContractState":_ContractState,
                             @"CurrentPageSize":MORENCOUNT
                             };
    
    MCMyXiaJiBonusContractListModel * xiaJiBonusContractListModel = [[MCMyXiaJiBonusContractListModel alloc]initWithDic:x_dic];
    [xiaJiBonusContractListModel refreashDataAndShow];
    self.xiaJiBonusContractListModel = xiaJiBonusContractListModel;
    
    dispatch_group_async(group, quene, ^{
        
        xiaJiBonusContractListModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
            dispatch_semaphore_signal(semaphore);
            NSLog(@"complete task 2-NO");
            
        };
        xiaJiBonusContractListModel.callBackSuccessBlock = ^(id manager) {
            NSLog(@"complete task 2-YES");
            dispatch_semaphore_signal(semaphore);
            wself.T++;
            wself.dic2=manager;
        };
        
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    });
    
    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        if (wself.T>1) {
            
            compeletion(YES,wself.dic1,wself.dic2);
        }else{
            
            compeletion(NO,wself.dic1,wself.dic2);
        }
    });
}


-(void)loadXiaJi{
    [BKIndicationView showInView:self.view];
    __weak __typeof__ (self) wself = self;
    [self loadXiaJi:^(BOOL result, NSDictionary *data) {
        [BKIndicationView dismiss];
        [wself.tableView.mj_footer endRefreshing];
        [wself.tableView.mj_header endRefreshing];
        
        if (result) {
            
            [wself setXiaJiData:data];
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"加载失败"];
            wself.CurrentPageIndex=[NSString stringWithFormat:@"%d",[_CurrentPageIndex intValue]-1];
        }
    }];
}

#pragma mark-上拉加载更多
-(void)loadMoreData{
    _CurrentPageIndex=[NSString stringWithFormat:@"%d",[_CurrentPageIndex intValue]+1];
    [self loadXiaJi];
}
-(void)loadXiaJi:(Compeletion)compeletion{
 
    NSDictionary * dic = @{
                             @"searchName":@"",
                             @"TypeParameterId":_SystemType.Id,
                             @"CurrentPageIndex":_CurrentPageIndex,
                             @"ContractState":_ContractState,
                             @"CurrentPageSize":MORENCOUNT
                             };
    if (_subUserName.length>0) {
        dic = @{
                @"searchName":_subUserName,
                @"TypeParameterId":_SystemType.Id,
                @"CurrentPageIndex":_CurrentPageIndex,
                @"ContractState":_ContractState,
                @"CurrentPageSize":MORENCOUNT
                };
    }
    
    MCMyXiaJiBonusContractListModel * xiaJiBonusContractListModel = [[MCMyXiaJiBonusContractListModel alloc]initWithDic:dic];
    [xiaJiBonusContractListModel refreashDataAndShow];
    self.xiaJiBonusContractListModel = xiaJiBonusContractListModel;
    
    xiaJiBonusContractListModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        
        compeletion(NO,nil);
        
    };
    xiaJiBonusContractListModel.callBackSuccessBlock = ^(id manager) {
        
        compeletion(YES,manager);
        
    };
}


#pragma mark-数据处理
#pragma mark-下拉刷新 数据处理
-(void)setDataWithDic1:(NSDictionary *)dic1 andDic2:(NSDictionary *)dic2{
    
    [_xiaJiDataMarray removeAllObjects];
    
    MCMyBonusContractListDataModel* dataSource1 = [MCMyBonusContractListDataModel mj_objectWithKeyValues:dic1];
    _myBonusContractListData=dataSource1;
    self.headerView.dataSource = dataSource1;
    
    _xiajiListData = [MCMyXiaJiBonusContractListDataModel mj_objectWithKeyValues:dic2];
    
    _IsSubContract =[NSString stringWithFormat:@"%@",_xiajiListData.IsSubContract];
    
    //判断自身是否有新的分红契约：
    //get_sub_bonus_new  这个接口中， IsSubContract=1 并且  State =0 ，则提示有新的契约

    NSString * State = [NSString stringWithFormat:@"%@",dic2[@"State"]];
    if ([State isEqualToString:@"0"]&&[_IsSubContract isEqualToString:@"1"]) {
        [self.headerView setNewState:NO];
        _HaveNewContractState=YES;
    }else{
        [self.headerView setNewState:YES];
        _HaveNewContractState=NO;
    }

    self.headerView.frame=CGRectMake(0, 0, G_SCREENWIDTH, [MCBonusContractHeaderView computeHeight:_myBonusContractListData andLockState:_xiajiListData.LockState andHaveNewContractState:_HaveNewContractState]);
    
    self.headerView.lockState  = _xiajiListData.LockState;
    _LockState  = [NSString stringWithFormat:@"%@",_xiajiListData.LockState];
    
    if (_xiajiListData.ContractManagerModels.count<1) {
        self.tableView.mj_footer.hidden=YES;
    }else{
        [_xiaJiDataMarray addObjectsFromArray:_xiajiListData.ContractManagerModels];

    }
    if (_xiajiListData.ContractManagerModels.count%[MORENCOUNT integerValue]!=0) {
        self.tableView.mj_footer.hidden=YES;
    }else{
        self.tableView.mj_footer.hidden=NO;
    }
    [_tableView reloadData];
}


-(void)setXiaJiData:(NSDictionary *)dic{
    
    _xiajiListData = [MCMyXiaJiBonusContractListDataModel mj_objectWithKeyValues:dic];
    _IsSubContract =[NSString stringWithFormat:@"%@",_xiajiListData.IsSubContract];

    if (_xiajiListData.ContractManagerModels.count<1) {
        self.tableView.mj_footer.hidden=YES;
        [_tableView reloadData];
        return;
    }
    if (_xiajiListData.ContractManagerModels.count%[MORENCOUNT integerValue]!=0) {
        self.tableView.mj_footer.hidden=YES;
    }
    
    [_xiaJiDataMarray addObjectsFromArray:_xiajiListData.ContractManagerModels];
    
    [_tableView reloadData];
    
}

#pragma mark-Tool
-(NSArray *)GetTouchArrayWithState:(NSString *)State{
    
//    //数组第一个为状态内容，第二个为按钮内容。
//    switch (State){
//        case 0:
//            return ['待确认','修改契约'];
//        case 1:
//            return ['已签约','修改契约'];
//        case 2:
//            return ['未签约','签订契约'];
//    }
    NSString * str1=@"";
    if ([[NSString stringWithFormat:@"%@",State]isEqualToString:@"2"]) {
        str1=@"签订契约";
    }else{
        str1=@"更改契约";
    }
    
//    备注：
//    判断某下级用户是否有“分红结算”：（注意：LockState 是data下的，不是列表里的 ）
//    当 LockState == 1 && State != 2，则显示“分红结算”按钮，否则不显示。

    if ([_LockState intValue]== 1 && [State intValue] != 2) {
        return @[@"分红结算",str1];
    }else{
        return @[str1];
    }
    
    

}

#pragma mark-set/get
- (MCNaviSelectedPopView *)popView1{
    
    if (_popView1 == nil) {
        MCNaviSelectedPopView * popView1 = [[MCNaviSelectedPopView alloc]InitWithType:MCNaviSelectedPopType_BonusContract];
        UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap1)];
        [popView1 addGestureRecognizer:tap1];
        [self.navigationController.view addSubview:popView1];
        _popView1 = popView1;
    }
    return _popView1;
}
-(MCBonusContractHeaderView *)headerView{
    if (!_headerView) {
        _headerView=[[MCBonusContractHeaderView alloc]init];
    }
    return _headerView;
}
- (void)tap1{
    _isShowPopView1=NO;
    [self dismissAllPopView1];
}
-(void)dismissAllPopView1{
    [self.popView1 dismiss];
    [self.viewPop1 hiden];
}
- (MCMMIputView *)viewPop1{
    if (_viewPop1 == nil) {
        
        MCMMIputView *viewStatus = [[MCMMIputView alloc] init];
        [self.navigationController.view addSubview:viewStatus];
        _viewPop1 = viewStatus;
    }
    return _viewPop1;
}

@end
















































